package com.github.phoenics.militia.bazookaFx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.phoenics.militia.bazookaFx.domain.entity.App;
import com.github.phoenics.militia.bazookaFx.domain.entity.AppTable;
import com.github.phoenics.militia.bazookaFx.domain.entity.SchemaTablesView;
import com.github.phoenics.militia.bazookaFx.domain.enums.DatabaseType;
import com.github.phoenics.militia.bazookaFx.model.AppModel;
import com.github.phoenics.militia.bazookaFx.model.AppTableModel;
import com.github.phoenics.militia.bazookaFx.service.AppService;
import com.github.phoenics.militia.bazookaFx.service.AppTableService;
import com.github.phoenics.militia.bazookaFx.service.SchemaNameViewService;
import com.github.phoenics.militia.bazookaFx.service.SchemaTablesViewService;
import com.github.phoenics.militia.common.utils.ValidationUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.controlsfx.validation.Severity;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * @author Phoenics Chow
 * on 2019年01月30日
 */
@FXMLController
public class EditAppController implements Initializable {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(EditAppController.class);
    public static final IntegerProperty tagFire=new SimpleIntegerProperty(0);
    private ValidationSupport validationSupport = new ValidationSupport();
    @Autowired
    SchemaNameViewService schemaNameViewService;
    @Autowired
    MainLaunchController mainLaunchController;
    @Autowired
    AppService appService;
    @Autowired
    AppTableService appTableService;
    @Autowired
    SchemaTablesViewService schemaTablesViewService;



    @FXML
    TextField projectName;
    @FXML
    TextField projectCnName ;
    @FXML
    ComboBox<DatabaseType> dbType;
    @FXML
    ComboBox<String> schema;
    @FXML
    TextField dfPackageHead ;
    @FXML
    TextField modelName ;
    @FXML
    TextField author ;
    @FXML
    TextField email ;
    @FXML
    TextField tablePrefix ;
    @FXML
    TextField projectPath ;
    @FXML
    TextArea projectComment;

    ObservableList< String> schemaList=FXCollections.observableArrayList();
    private AppModel appModel=new AppModel();
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        registerValidator();
        schema.setItems(schemaList);
        dbType.getItems().addAll(DatabaseType.values());
        getSchemas();
        appModel.clear();
        tagFire.addListener((ob,o,n)-> {
            getSchemas();
            appModel.clear();
        });
        bindEvent();
    }

    private void bindEvent(){
        projectName.textProperty().bindBidirectional(appModel.appNameProperty());
        projectCnName.textProperty().bindBidirectional(appModel.appCnNameProperty());
        dbType.valueProperty().bindBidirectional(appModel.dbTypeProperty());
        schema.valueProperty().bindBidirectional(appModel.schemaNameProperty());
        dfPackageHead.textProperty().bindBidirectional(appModel.dfPackageHeadProperty());
        modelName.textProperty().bindBidirectional(appModel.modelNameProperty());
        author.textProperty().bindBidirectional(appModel.authorProperty());
        email.textProperty().bindBidirectional(appModel.emailProperty());
        tablePrefix.textProperty().bindBidirectional(appModel.tablePrefixProperty());
        projectPath.textProperty().bindBidirectional(appModel.appPathProperty());
        projectComment.textProperty().bindBidirectional(appModel.appCommentProperty());
    }

    public void closeWindow(ActionEvent event){
        ((Stage)((Button)event.getTarget()).getScene().getWindow()).close();
    }

    public void showInfo(ActionEvent event){
        if(!validationSupport.isInvalid()){
            App app=new App();
            appService.save(appModel.takeObjectWarpper(app));
            insertSchemaTable(app.getSchemaName(),app.getId());
            mainLaunchController.reloadAppTree();
        }
        ((Stage)((Button)event.getTarget()).getScene().getWindow()).close();
    }

    private void getSchemas(){
        List<String> list=schemaNameViewService.list().stream().map(o->o.getSchemaName()).collect(Collectors.toList());
        schemaList.clear();
        schemaList.addAll(list);
    }

    private void registerValidator(){
        validationSupport.registerValidator(projectName, Validator.createRegexValidator("项目代码不能为空，并且不能重复",ValidationUtil.STR_ENG_NUM_,Severity.ERROR));
        validationSupport.registerValidator(projectCnName, Validator.createEmptyValidator("项目中文名不能为空"));
        //validationSupport.registerValidator(dbType, Validator.createEmptyValidator("项目代码不能为空，并且不能重复"));
        validationSupport.registerValidator(dfPackageHead, Validator.createRegexValidator("java包标示不对",ValidationUtil.JAVAPACKAGE,Severity.ERROR));
        validationSupport.registerValidator(modelName, Validator.createRegexValidator("模块名称", ValidationUtil.JAVAPACKAGE,Severity.ERROR));
        //validationSupport.registerValidator(author, Validator.createEmptyValidator("项目代码不能为空，并且不能重复"));
        validationSupport.registerValidator(email, Validator.createRegexValidator("email格式错误", ValidationUtil.EMAIL, Severity.ERROR));
    }

    private void insertSchemaTable(String schemaName,Long appId){
        QueryWrapper<SchemaTablesView> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("table_schema",schemaName);
        List<AppTable> modelLists=schemaTablesViewService.list(queryWrapper).stream().map(i->{
            AppTable appTable=new AppTable();
            appTable.setAppId(appId);
            appTable.setTableName(i.getTableName());
            appTable.setTableCnName(i.getTableComment());
            appTable.setTableComment(i.getTableComment());
            appTable.setCreateTime(i.getCreateTime());
            return appTable;
        }).collect(Collectors.toList());
        appTableService.saveBatch(modelLists);
    }
}
